package com.az.zhaotao.wxqf;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.text.method.ScrollingMovementMethod;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.az.zhaotao.wxqf.util.SharedHelper;
import com.az.zhaotao.wxqf.util.SystemEnum;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import cn.zhouyafeng.itchat4j.api.WechatTools;
import cn.zhouyafeng.itchat4j.controller.MultiCoreLoginController;
import cn.zhouyafeng.itchat4j.core.MultiCore;
import cn.zhouyafeng.itchat4j.thread.ThreadUsers;


public class MainActivity extends Activity {
    private Button refreshButton;
    private SharedHelper sh;
    private Context mContext;
    private ImageView qrView;
    private Handler handler;

    private Bitmap bitmap;
    private TextView logTextView;

    private String urlMsg;
    private String logMsg;
    private Switch aSwitch;

    //标题
    private Button titleSubmitButton;
    private Button titleReturnButton;
    private TextView titleTitle;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getApplicationContext();
        sh = new SharedHelper(mContext);
        setContentView(R.layout.activity_main);

        refreshButton = findViewById(R.id.refreshButton);
        qrView = findViewById(R.id.imageView2);
        logTextView = findViewById(R.id.logTextView);
        aSwitch = findViewById(R.id.qfswitch);
        titleSubmitButton = findViewById(R.id.title_button_forward);
        titleReturnButton = findViewById(R.id.title_button_backward);
        titleTitle = findViewById(R.id.text_title);
        logTextView.setMovementMethod(ScrollingMovementMethod.getInstance());//设置logView可滚动

        //设置标题
        titleTitle.setText("群发助手");
        titleReturnButton.setVisibility(View.GONE);
        titleReturnButton.setWidth(0);
        titleSubmitButton.setText("设置");
        titleSubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this,SettingActivity.class);
                startActivity(intent);
            }
        });

        handler=new Handler();
        /**
         * 打开大图
         */
        qrView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null == bitmap) {
                    return;
                }else {
                    Intent intent=new Intent(MainActivity.this,BigImageActivity.class);
                    ByteArrayOutputStream baos=new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    byte [] bitmapByte =baos.toByteArray();
                    intent.putExtra("bitmap", bitmapByte);
                    startActivity(intent);
                    overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
                }
            }
        });

        /**
         * 刷新按钮
         */
        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(){
                    public void run(){
                        String key = ThreadUsers.getNextKey(); //每次刷新获取一个新的key
                        MultiCore.remove(key);//清除旧登陆信息
                        //获取二维码
                        MultiCoreLoginController login = new MultiCoreLoginController(key);
                        urlMsg = login.getQrUrl();
                        InputStream is;
                        try {
                            is = new URL(urlMsg).openStream();
                            bitmap = BitmapFactory.decodeStream(is);
                            logMsg = key+"获取二维码成功\n";
                            handler.post(logTextRunnable);
                            handler.post(imageRunnable); //展示二维码
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        //登陆
                        if (login.login()) { //登陆成功
                            String msg = (String) sh.read().get(SystemEnum.EditText.getKey());
                            if (msg == null) {
                                msg =getResources().getString(R.string.rsyyjsd);
                            }
                            logMsg = key + "登陆成功，正在进行初始化...\n";
                            handler.post(logTextRunnable);
                            login.init();
                            logMsg = key + "初始化完成，进行群发\n";
                            handler.post(logTextRunnable);
                            String switchValue = (String) sh.read().get(SystemEnum.QfSwitch.getKey());
                            if (null != switchValue && "true".equals(switchValue)) {
                                logMsg = key + "预计"+login.getCore().getContactList().size()+"秒\n";
                                handler.post(logTextRunnable);
                                login.qunfa(msg,true);
                            }else {
                                login.qunfa(msg,false);
                            }
                            logMsg = key + "群发完成\n";
                            handler.post(logTextRunnable);
                        }else{ //登陆失败
                            logMsg = key + "登陆失败";
                            handler.post(logTextRunnable);
                        }
                        //MultiCore.remove(key);//清除登陆信息
                    }
                }.start();
            }
        });
        /**
         * 选择是否群发
         */
        String switchValue = (String) sh.read().get(SystemEnum.QfSwitch.getKey());
        if (null != switchValue && "true".equals(switchValue)) {
            aSwitch.setChecked(true);
        }else {
            aSwitch.setChecked(false);
        }
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    sh.save(SystemEnum.QfSwitch.getKey(),"true");
                }else {
                    sh.save(SystemEnum.QfSwitch.getKey(),"false");
                }
            }
        });
    }

    Runnable imageRunnable = new Runnable(){
        @Override
        public void run() {
            qrView.setImageBitmap(bitmap);
        }
    };

    Runnable logTextRunnable = new Runnable() {
        @Override
        public void run() {
            logTextView.append(logMsg);
            int offset=logTextView.getLineCount()*logTextView.getLineHeight();
            if(offset>logTextView.getHeight()){
                logTextView.scrollTo(0,offset-logTextView.getHeight());
            }
        }
    };


}
